package com.lzp.java.concurrent.threadcore.threadandobject.object;

/**
 * wait和notify使用
 * 1. 代码执行顺序
 * 2. 证明wait释放锁
 *
 * @author lzp
 * @date 2020/02/04
 */
public class WaitAndNotify {
    private static Object object = new Object();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + "--获取到object的monitor锁--" + Thread.currentThread().getState());
                try {
                    Thread.sleep(1000);
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "--再次获取到object的monitor锁--" + Thread.currentThread().getState());
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + "--获取到object的monitor锁--" + Thread.currentThread().getState());
                object.notify();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        thread1.start();
        Thread.sleep(100);
        Thread2 thread2 = new Thread2();
        thread2.start();
        Thread.sleep(100);
        System.out.println(thread2.getName() + "--等待object的monitor锁--" + thread2.getState());
        Thread.sleep(1000);
    }
}
